#include <iostream>
#include <string>
#include <memory>
#include <ctime>
#include "socket.hpp"
#include "Protocol.hpp"
#include "InetAddr.hpp"

using namespace std;
using namespace protrol;
using namespace socket_net;

void usage(string proc)
{
    cout << "Usage:\n\t" << proc << " local_port\n"
         << endl;
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        usage(argv[0]);
        exit(1);
    }
    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);
    // 同样的创建套接字----->用来发消息
    InetAddr serveraddr(serverip, serverport);
    Factory fac;
    unique_ptr<Socket> Cli = make_unique<TcpSocket>();
    // 创建Client的套接字
    bool res = Cli->BuildClientSocket(serveraddr);
    string inbuffer;
    while (res)
    {
        sleep(1);
        auto req = fac.BulidRequest();
        // 进行序列化
        string send_str;
        req->Serialization(&send_str);
        cout << "Serialization: \n"
             << send_str << endl;
        // 进行添加长度
        send_str = Encode(send_str);
        cout << "Encode :\n"
             << send_str << endl;
        // 进行发送
        Cli->Send(send_str);
        // 进行读操作
        int n = Cli->Recv(&inbuffer);
        if (n <= 0)
            break;
        string package = Decode(inbuffer); // 输出一个报文
        if (package.empty())
            continue;
        auto resp = fac.BuildResponse();
        resp->Deserialization(package);
        std::cout << resp->_res << "[" << resp->_code << "]" << std::endl;
    }
}
